package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"seckill/global/model"
	"seckill/internal/svc"
	"seckill/seckill"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SecKillListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSecKillListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SecKillListLogic {
	return &SecKillListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

type T struct {
	ActivityId   int       `json:"activityId"`
	ProductId    int       `json:"productId"`
	SeckillPrice int       `json:"seckillPrice"`
	SeckillStock int       `json:"seckillStock"`
	StartTime    time.Time `json:"startTime"`
	EndTime      time.Time `json:"endTime"`
	Status       string    `json:"status"`
}

func (l *SecKillListLogic) SecKillList(in *seckill.SecKillListRequest) (*seckill.SecKillListResponse, error) {
	// todo: add your logic here and delete this line
	keys := model.RDB.Keys(model.Ctx, "*:seckill:*").Val()
	var Srckills []*seckill.SecKill
	for _, key := range keys {
		var k T
		fmt.Println(key)
		data := model.RDB.Get(model.Ctx, key).Val()
		fmt.Println(data)
		json.Unmarshal([]byte(data), &k)
		pk := fmt.Sprintf("product:%d", k.ProductId)
		p_data := model.RDB.Get(model.Ctx, pk).Val()
		var pro model.Product
		json.Unmarshal([]byte(p_data), &pro)
		var src = seckill.SecKill{
			Title:        pro.Name,
			Stock:        int64(k.SeckillStock),
			LostTime:     k.EndTime.String(),
			ProductId:    int64(k.ProductId),
			ProductPrice: float32(k.SeckillPrice),
			ProductUrl:   pro.ImgUrl,
			ProductClass: fmt.Sprintf("%d", pro.CategoryId),
		}
		Srckills = append(Srckills, &src)
	}
	return &seckill.SecKillListResponse{
		Seckills: Srckills,
	}, nil
}
